package leetcode.leetcode_707;


class MyLinkedList {
    class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
        }
    }

    private int size;
    //    虚拟头节点
    private ListNode head;

    public MyLinkedList() {
        this.size = 0;
        this.head = new ListNode(0);

    }

    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }
        ListNode curr = head;
        for (int i = 0;i<=index;i++){
            curr = curr.next;
        }
        return curr.val;
    }

    /**
     * 添加头节点
     * @param val
     */
    public void addAtHead(int val) {
        ListNode listNode = new ListNode(val);
        listNode.next = head.next;
        head.next = listNode;
        size++;
    }

    /**
     * 在尾节点添加节点
     * @param val
     */
    public void addAtTail(int val) {
        ListNode listNode = new ListNode(val);
        ListNode curr = head;
        while(curr.next!=null){
            curr = curr.next;
        }
        curr.next = listNode;
        size++;
    }

    public void addAtIndex(int index, int val) {
        if (index>size||index<0){
            return;
        }
        ListNode node = new ListNode(val);
        ListNode curr = head;
        for (int i =0 ; i<index;i++){
            curr = curr.next;
        }
        node.next = curr.next;
        curr.next = node;
        size++;

    }

    public void deleteAtIndex(int index) {
        if (index >= size){
            return ;
        }
        if (index < 0 ){
            return;
        }
        ListNode curr = head;
        for (int i =0 ;i<index ;i++){
            curr = curr.next;
        }
        curr.next = curr.next.next;
        size--;
    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */